<template>
  <NpDialog :visible.sync="dialogPvVisible" width="608px" class="container">
    <template>
      <div class="title">新增/编辑账号</div>
      <div class="con">
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleFormRef" label-width="86px">
          <el-form-item label="登录账号" prop="username">
            <el-input v-model="ruleForm.username" placeholder="请输入登录账号，可输入字母或数字" @input="username_input"></el-input>
          </el-form-item>
          <el-form-item label="品牌" prop="menufacturerId">
            <el-select v-model="ruleForm.menufacturerId" placeholder="请选择账号所属的品牌">
              <el-option v-for="(item, index) in brandOptions" :key="'br' + index" :label="item.menufacturer"
                :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="ruleForm.role" placeholder="请选择账号所属角色" clearable>
              <el-option v-for="(item, index) in UserRolesOptions" :key="'br' + index" :label="item.userName"
                :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="密码" key="password" :prop="isAdd ? 'password' : ''">
            <el-input v-model="ruleForm.password" placeholder="请输入6-20位的登录密码" maxlength="20"
              @input="password_input_static($event, 'ruleForm.password')"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phoneNum">
            <el-input v-model="ruleForm.phoneNum" placeholder="请输入账号的手机号" @input="phoneNum_input"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="ruleForm.remarks" placeholder="请输入账号的备注信息"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="fotter">
        <el-button type="info" plain class="btn1" @click="uploadCancelClick">取消</el-button>
        <el-button type="warning" @click="uploadImportClick('ruleFormRef')" :loading="submitLoading">确定</el-button>
      </div>
    </template>
  </NpDialog>
</template>
<script>
import NpDialog from "@/components/np/Dialog/index.vue"
import { md5 } from "js-md5";
import { password_input_static } from '@/utils/mixins'
import {
  puserAddPuser,
  puserUpdatePuser,
} from '@/api/backend-account-management/account/list'

export default {
  mixins: [password_input_static],
  components: {
    NpDialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    brandOptions: {
      type: Array,
      default: () => {
        return []
      }
    },
    UserRolesOptions: {
      type: Array,
      default: () => {
        return []
      }
    },
    infoRow: {
      type: Object,
      default: () => {
        return null
      }
    }
  },
  data() {
    let com_blur__rule = [{ required: true, message: '此字段为必填。', trigger: 'blur' }],
      com_change__rule = [{ required: true, message: '此字段为必填。', trigger: 'change' }];
    let password__validate = (rule, value, callback) => {
      if (!value || value.length <= 5) {
        callback(new Error("请输入6-20位的登录密码"));
        return;
      }
      callback();
    };
    return {
      dialogPvVisible: false,

      submitLoading: false,
      ruleForm: {
        username: '', // 这个字段后台没有,要对后端
        menufacturerId: '',
        role: '', // 这个字段暂时没有，2期弄
        password: '',
        phoneNum: '',
        remarks: '',// 这个字段后台没有,要对后端
      },
      rules: {
        username: com_blur__rule,
        menufacturerId: com_change__rule,
        role: com_change__rule,
        password: [{
          required: true,
          validator: password__validate,
          trigger: "blur",
        }],
      },
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        this.dialogPvVisible = newVal;
        if (newVal) {
          if (this.infoRow) {
            this.editInfo()
            this.rules.password[0].required = false
            return
          }
        }
        if (!newVal) {
          this.resetFieldsFrom()
        }
      }
    }
  },
  computed: {
    // ...mapGetters({
    //   introduction: 'introduction'
    // }),
    isEdit() {
      return !!this.infoRow
    },
    isAdd() {
      return !this.infoRow
    },
    isModifiedData() {
      if (this.isEdit) {
        try {
          let arr = Object.keys(this.ruleForm);
          let v = arr.find(el => {
            let fd = this.ruleForm[el],
              rd = this.infoRow[el];
            if (!fd && !rd) {
              return false
            }
            return this.ruleForm[el] !== this.infoRow[el]
          })
          return !v
        } catch (error) { }
      }
      return false
    }
  },
  created() { },
  methods: {
    editInfo() {
      let arr1 = Object.keys(this.ruleForm);
      let noValArr = ['password']
      arr1.forEach(el => {
        if (noValArr.includes(el)) {
          return
        }
        this.ruleForm[el] = this.infoRow[el] || this.ruleForm[el]
      })
    },
    resetFieldsFrom() {
      this.rules.password[0].required = true
      Object.keys(this.ruleForm).forEach(el => {
        this.ruleForm[el] = ''
      })
    },
    uploadCancelClick() {
      this.dialogPvVisible = false
      this.submitLoading = false
      this.$refs['ruleFormRef'].resetFields()
      this.$emit("update:visible", this.dialogPvVisible)
    },
    uploadImportClick(formName) {
      if (this.isModifiedData) {
        this.$message.error('数据未有更改，关闭当前弹窗。')
        this.uploadCancelClick()
        return
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = { ...this.ruleForm },
            fun = puserAddPuser;
          let pw = params.password
          if (pw) {
            if (pw.length <= 5 || pw.length > 20) {
              this.$message.error('修改密码时，请输入6-20位的登录密码。')
              return
            }
          } else {
            delete params.password
          }

          if (this.isEdit) {
            fun = puserUpdatePuser;
            params.id = this.infoRow.id || ''
            if (params.username === this.infoRow.username) {
              delete params.username
            }
          }
          if (this.isAdd) {
            params.status = 1
          }
          let need_int = ['role'];
          params.role = parseInt(params.role)
          params.password = md5(params.password)

          this.submitLoading = true
          fun(params).then(res => {
            if (res.code === 200) {
              let data = this.isEdit ? 'edit' : 'add',
                obj = {
                  add: '新增',
                  edit: '编辑',
                };
              this.$message.success(`${obj[data]}成功!`)
              setTimeout(() => {
                this.uploadCancelClick()
                this.$emit("editAddSuccessChange", data)
              }, 2000)
              return
            } else {
              this.$message.error(`${obj[data]}失败。`)
            }
            this.submitLoading = false
          }).catch(err => {
            this.$message.error('系统错误，服务失败。')
            this.submitLoading = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    username_input(e) {
      e = e.replace(/[^a-zA-Z0-9]/g, '');
      this.ruleForm.username = e
    },
    phoneNum_input(e) {
      e = e.replace(/[^0-9]/g, '');
      this.ruleForm.phoneNum = e
    },
  }
}
</script>
<style lang="scss" scoped>
.title {
  padding-bottom: 32px;
  font-size: 18px;
  font-weight: 500;
  line-height: 24px;
  color: #15181D;
}

.fotter {
  padding-top: 12px;
  display: flex;
  justify-content: right;
  align-items: center;

  .btn1 {
    margin-right: 12px;
  }
}

.container {
  ::v-deep {
    @media (max-width: 1280px) {
      .np-el-d-body {
        padding: 24px 40px 40px 24px;
      }
    }
  }
}

::v-deep {
  .con {
    .el-form-item__label {
      font-size: 14px;
      font-weight: normal;
      color: #8B8B8B;
    }

    .el-select,
    .el-date-editor {
      width: 100%;
    }
  }
}
</style>